package com.neusoft.nepc.controller;


import com.neusoft.nepa.UserLogin;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class TestViewController {
    @FXML
    private ImageView bgImageView;
    @FXML
    private Button btn1;
    @FXML
    private TextField so2;
    @FXML
    private TextField co;
    @FXML
    private TextField pm2_5;
    @FXML
    private TextField so2AQI;
    @FXML
    private TextField coAQI;
    @FXML
    private TextField pm2_5AQI;
    @FXML
    private TextField result;
    @FXML
    private Button work;
    private final String[] AQI_LEVELS = {"一级", "二级", "三级", "四级", "五级", "六级"};
    @FXML private TextField usernameField;
    @FXML private TextField networkField;
    @FXML private TextField detailsField;
    @FXML private TextField estimatedLevelField;
    @FXML private TextField descriptionField;

    private String currentProvince;
    private String currentCity;
    private boolean so2if;
    private boolean coif = false;
    private boolean pm25if = false;

    public void initData(AdminViewController.Task task) {
        if( usernameField!=null&&task!=null) {
            usernameField.setText(task.getUsername());
            networkField.setText(task.getRegion());
            detailsField.setText(task.getDetails());
            estimatedLevelField.setText(task.getEstimatedLevel());
            descriptionField.setText(task.getDescription());
            String[] temp = task.getRegion().split("__");
            currentProvince = temp[0];
            currentCity = temp[1];
        }
    }

    @FXML
    public void initialize() {
        Image bgImage = new Image("com/neusoft/nepc/Image/envi1.jpg");
        bgImageView.setImage(bgImage);
        bgImageView.setPreserveRatio(false);
        bgImageView.setSmooth(true);
    }

    @FXML
    private void back(ActionEvent event) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader();
        fxmlLoader.setLocation(getClass().getResource("../view/AdminView.fxml"));
        Parent registerRoot = fxmlLoader.load();

        Stage stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
        Scene registerScene = new Scene(registerRoot);
        stage.setScene(registerScene);
        stage.show();
    }

    @FXML
    public int getAQI() {
        try {
            double so2range = parseDouble(so2.getText());
            double corange = parseDouble(co.getText());
            double pm25range = parseDouble(pm2_5.getText());


            int so2Level = calculatePollutantLevel(so2range, new double[]{0, 50, 150, 475, 800, 1600});
            int coLevel = calculatePollutantLevel(corange, new double[]{0, 5, 10, 35, 60, 90});
            int pm25Level = calculatePollutantLevel(pm25range, new double[]{0, 35, 75, 115, 150, 250});

            so2if = (so2Level>3);
            coif = (coLevel>3);
            pm25if = (pm25Level>3);

            int finalLevel = Math.max(so2Level, Math.max(coLevel, pm25Level));

            so2AQI.setText(AQI_LEVELS[so2Level]);
            coAQI.setText(AQI_LEVELS[coLevel]);
            pm2_5AQI.setText(AQI_LEVELS[pm25Level]);
            result.setText(AQI_LEVELS[finalLevel]);

            return AQICalculator.calculateAQI(so2range,corange,pm25range);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private double parseDouble(String text) throws NumberFormatException {
        if (text == null || text.trim().isEmpty()) {
            return 0;
        }
        return Double.parseDouble(text.trim());
    }

    private int calculatePollutantLevel(double concentration, double[] thresholds) {
        for (int i = 0; i < thresholds.length - 1; i++) {
            if (concentration >= thresholds[i] && concentration <= thresholds[i+1]) {
                return i;
            }
        }
        if (concentration > thresholds[thresholds.length - 1]) {
            return thresholds.length - 1;
        }
        return 0;
    }
    @FXML
    public void confirmAndUpdateAQI() {

        int aqiIndex = getAQI(); // 获取实际 AQI 指数
        System.out.println(aqiIndex);
        String province_tool = "_";
        if (so2if) province_tool += "1";
        else province_tool += "0";
        province_tool += "_";
        if (coif) province_tool += "1";
        else province_tool += "0";
        province_tool += "_";
        if (pm25if) province_tool += "1";
        else province_tool += "0";
        province_tool += "_";
        if (so2if||coif||pm25if) province_tool += "1";
        else province_tool += "0";

        try {
            UserLogin userLogin = new UserLogin();
            currentProvince = currentProvince+"省";
            String new_province_tool = currentProvince + province_tool;
            boolean temp = userLogin.updateDataListAQILevel(currentProvince, currentCity, aqiIndex, new_province_tool);
            if (!temp) {
                currentProvince = currentProvince.replace("省","市");
                userLogin.updateDataListAQILevel(currentProvince, currentCity, aqiIndex, new_province_tool);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class AQICalculator {
    // 浓度限值表（μg/m³，CO 为 mg/m³）
    private static final double[][] CONCENTRATION_LIMITS = {
            // PM2.5   SO₂     CO
            {0,      0,      0},      // IAQI 0
            {35,     150,    5},      // IAQI 50
            {75,     500,    10},     // IAQI 100
            {115,    650,    35},     // IAQI 150
            {150,    800,    60},     // IAQI 200
            {250,    1600,   90},     // IAQI 300
            {350,    2100,   120},    // IAQI 400
            {500,    2620,   150}     // IAQI 500
    };

    // AQI 限值
    private static final int[] AQI_LIMITS = {0, 50, 100, 150, 200, 300, 400, 500};

    /**
     * 根据 SO₂、CO、PM2.5 三个污染物浓度计算 AQI
     * @param so2 SO₂ 浓度 (μg/m³)
     * @param co CO 浓度 (mg/m³)
     * @param pm25 PM2.5 浓度 (μg/m³)
     * @return 最终 AQI 值
     */
    public static int calculateAQI(double so2, double co, double pm25) {
        int iaqiSO2 = calculateIAQI(so2, 1); // 1 对应 SO₂ 在限值表中的索引
        int iaqiCO = calculateIAQI(co, 2);   // 2 对应 CO 在限值表中的索引
        int iaqiPM25 = calculateIAQI(pm25, 0); // 0 对应 PM2.5 在限值表中的索引

        // 最终 AQI 为各项污染物 IAQI 的最大值
        return Math.max(Math.max(iaqiSO2, iaqiCO), iaqiPM25);
    }

    /**
     * 计算单个污染物的 IAQI
     * @param concentration 污染物浓度
     * @param pollutantIndex 污染物在 CONCENTRATION_LIMITS 中的索引
     * @return 对应的 IAQI 值
     */
    private static int calculateIAQI(double concentration, int pollutantIndex) {
        int index = 0;

        // 找到浓度所在的区间
        for (int i = 1; i < CONCENTRATION_LIMITS.length; i++) {
            if (concentration <= CONCENTRATION_LIMITS[i][pollutantIndex]) {
                index = i;
                break;
            }
            if (i == CONCENTRATION_LIMITS.length - 1) {
                index = i; // 超过最高限值时使用最后一个区间
            }
        }

        double bpLo = CONCENTRATION_LIMITS[index - 1][pollutantIndex];
        double bpHi = CONCENTRATION_LIMITS[index][pollutantIndex];
        int iaqiLo = AQI_LIMITS[index - 1];
        int iaqiHi = AQI_LIMITS[index];

        // 计算 IAQI
        if (bpHi == bpLo) {
            return iaqiHi; // 防止除零错误
        }
        return (int) Math.round(((iaqiHi - iaqiLo) / (bpHi - bpLo)) * (concentration - bpLo) + iaqiLo);
    }

    public static void main(String[] args) {
        // 示例：SO2=100, CO=2.5, PM2.5=60
        double so2 = 100;   // μg/m³
        double co = 2.5;    // mg/m³
        double pm25 = 60;   // μg/m³

        int aqi = calculateAQI(so2, co, pm25);
        System.out.println("AQI: " + aqi); // 输出应为 83
    }
}